package com.wave.gate.init;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.wave.gate.enums.ConveyerEnum;
import com.wave.gate.enums.RedisKeyEnum;
import com.wave.gate.mqtt.client.MqttSendClient;
import com.wave.gate.netty.NettyServer;
import com.wave.gate.task.Server;
import com.wave.gate.util.*;
import com.wave.gate.vo.GatePassSetVo;
import com.wave.gate.vo.GatePassWeightParamVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.*;

/**
 * @author TanLei
 * @className：InitBaseInfo
 * @description：TODO
 * @date 2023/5/5 20:58
 * @version: 1.0
 */
@Slf4j
@Component
public class InitBaseInfo {

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private MqttSendClient mqttSendClient;

    @Value("${wave.door.security.http}")
    private String http;

    @Value("${electronicBalance.mobile.error}")
    private Double mobileError;

    @Value("${electronicBalance.token.error}")
    private Double tokenError;

    @Value("${face.type}")
    private int faceType;
    private final String LINUX_CMD_SN = "wsn read";
    public static String ipAddress = "";
    public static Map<String, String> modelPathMap= new HashMap<String, String>();

    public static Map<String, String> roiTypeMap= new HashMap<String, String>();


    public static String sn = "";
    @PostConstruct
    public void init() {
        try {
            //设置闸机为核验模式
            GuavaCache.DOOR_MODE_CACHE.put(RedisKeyEnum.KEY_REMOTE_CONTROLL.getCode(), 1);
            boolean linux = System.getProperty("os.name").toLowerCase().contains("linux");
            if(linux){
                ipAddress = GetLocalHost.getIpDetails().getIpv4Inet();
                log.info("本机ip：{}",ipAddress);

                sn = exeCmd(LINUX_CMD_SN);
                sn = sn.substring(0,11);

                String url = http + "/wave-gate/devicesnip";
                // 3. 设置请求参数   前后端约定通过json格式传递参数，此时就不能用form方法了，改用它提供的body方法
                Map<String, Object> paramsMap = new HashMap<>();
                paramsMap.put("deviceIP",ipAddress);
                paramsMap.put("deviceSn",sn);
                HttpResponse execute = HttpUtils.httpCache(url, paramsMap);
                String body = execute.body();   // 获取响应主体
                log.info("项目启动更新后台管理系统ip和sn的关系结果：" + body);

            }

            Socket conveyer = null;
            try {
                String url = http + "/wave-gate/device/cache";
                //设置请求参数   前后端约定通过json格式传递参数，此时就不能用form方法了，改用它提供的body方法
                Map<String, Object> paramsMap = new HashMap<>();
                paramsMap.put("deviceIP", StringUtils.isEmpty(ipAddress) ?"192.168.1.155":ipAddress);
                paramsMap.put("queryIps", 2);
                paramsMap.put("queryWeight", 2);
                paramsMap.put("mobileError", mobileError);
                paramsMap.put("tokenError", tokenError);
                HttpResponse execute = HttpUtils.httpCache(url, paramsMap);
                String body = execute.body();   // 获取响应主体
                log.info("项目启动该套设备的ip集合/手机、token重量误差集合结果：" + body);
                if(execute.isOk()){
                    Map<String, String> map = JSON.parseObject(body, HashMap.class);
                    if("200".equals(map.get("code"))) {
                        GuavaCache.PASSSET_CACHE.put("passsetipInfo", JSON.parseObject(map.get("passsetipInfo"), GatePassSetVo.class));
                        GuavaCache.MOBILE_TOKEN_WEIGHTLIST_CACHE.put("mobileTokenweightList",
                                JSON.parseArray(map.get("mobileTokenweightList"), GatePassWeightParamVo.class));

                        GatePassSetVo gatePassSetVo = GuavaCache.PASSSET_CACHE.getIfPresent("passsetipInfo");
                        //重置传送带
                        conveyer = new Socket(gatePassSetVo.getPclIp(), 502);
                        String str = SocketClientUtil.sendData(conveyer, ConveyerEnum.CONVEYER_COMMAND_M6.getCode());
                        log.info("重置传送带：[{}]",str);
                    }
                }

                if(faceType == 1){
                    log.info("开始启动人脸识别服务端");
                    threadPoolTaskExecutor.execute(Server::new);
                    log.info("人脸识别服务端启动成功");
                }
                if(faceType == 2){
                    log.info("开始启动人脸识别服务端（串口转网口）");
                    threadPoolTaskExecutor.execute(()->{
                        NettyServer.startFaceServer(mqttSendClient, threadPoolTaskExecutor);
                    });
                    log.info("人脸识别服务端启动成功（串口转网口）");
                }


            } catch (Exception ex) {
                log.error("传送带/人脸识别服务端报错：[{}]", ex.getMessage(), ex);
            }finally {
                if(conveyer != null){
                    try {
                        conveyer.close();
                    } catch (IOException e) {
                        log.error("关闭传送带报错：[{}]", e.getMessage(), e);
                    }
                }
            }

            modelPathMap.put("1640","已穿访客工衣");
            modelPathMap.put("1590","跨越");
            modelPathMap.put("1310","举手过肩");
            modelPathMap.put("1610","下蹲");
            modelPathMap.put("1600","弯腰");
            modelPathMap.put("1080","尾随");
            modelPathMap.put("1010","危险区域闯入");

            roiTypeMap.put("1","门外告警");
            roiTypeMap.put("2","门内告警");


        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取本地id地址异常");
        }
    }

    public String exeCmd(String commandStr) {

        String result = null;
        try {
            String[] cmd = new String[]{"/bin/sh", "-c",commandStr};
            Process ps = Runtime.getRuntime().exec(cmd);

            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                //执行结果加上回车
                sb.append(line).append("");
            }
            result = sb.toString();


        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;

    }


}
